<script lang="ts" name="Error" setup>
import pageError from '@/assets/svgs/404.svg'
import networkError from '@/assets/svgs/500.svg'
import noPermission from '@/assets/svgs/403.svg'
import { propTypes } from '@/utils/propTypes'
import { usePermissionStoreWithOut } from '@/store/modules/permission'

interface ErrorMap {
  url: string
  message: string
  buttonText: string
}

const { t } = useI18n()

const router = useRouter()

const defaultPath = ref('/')

const errorMap: {
  [key: string]: ErrorMap
} = {
  '404': {
    url: pageError,
    message: t('error.pageError'),
    buttonText: t('error.returnToHome')
  },
  '500': {
    url: networkError,
    message: t('error.networkError'),
    buttonText: t('error.returnToHome')
  },
  '403': {
    url: noPermission,
    message: t('error.noPermission'),
    buttonText: t('error.returnToHome')
  }
}

const props = defineProps({
  type: propTypes.string.validate((v: string) => ['404', '500', '403'].includes(v)).def('404')
})

const btnClick = () => {
  router.push({ path: defaultPath.value })
}

const getFullPath = (routers) => {
  const pathList: any[] = []
  const findPath = (routers, ppath = '') => {
    routers.forEach((e) => {
      if (e.children?.length) {
        const path = ppath ? `${ppath}/${e.path}` : `${ppath}${e.path}`
        findPath(e.children, path)
      } else {
        const path = ppath ? `${ppath}/${e.path}` : `${ppath}${e.path}`
        pathList.push(path)
      }
    })
  }
  findPath(routers)
  return pathList
}

const permissionStore = usePermissionStoreWithOut()
const dynamicRouter = permissionStore.getDynamicRouter
if (dynamicRouter.length) {
  defaultPath.value = getFullPath(dynamicRouter)[0]
}
</script>

<template>
  <div class="flex justify-center">
    <div class="text-center">
      <img :src="errorMap[type].url" alt="" width="350" />
      <div class="text-14px text-[var(--el-color-info)]">{{ errorMap[type].message }}</div>
      <div class="mt-20px">
        <ElButton type="primary" @click="btnClick">{{ errorMap[type].buttonText }}</ElButton>
      </div>
    </div>
  </div>
</template>
